package org.springframework.beans.extend;

import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.xml.*;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.core.io.support.EncodedResource;
import org.springframework.util.xml.SimpleSaxErrorHandler;
import org.springframework.util.xml.XmlValidationModeDetector;
import org.w3c.dom.Document;
import org.xml.sax.EntityResolver;
import org.xml.sax.ErrorHandler;
import org.xml.sax.InputSource;

import java.io.InputStream;

public class MyXmlBeanDefinitionReader extends XmlBeanDefinitionReader {



	protected MyXmlBeanDefinitionReader(BeanDefinitionRegistry registry) {
		super(registry);
		XmlBeanDefinitionReader reader2=new XmlBeanDefinitionReader(registry);
	}

	@Override
	public int loadBeanDefinitions(Resource resource)  {
		int count =0;
		try {
			EncodedResource encodedResource=new EncodedResource(resource);
			InputStream inputStream = encodedResource.getResource().getInputStream();
			org.xml.sax.InputSource inputSource = new org.xml.sax.InputSource(inputStream);

			Document doc = doLoadDocument(inputSource, resource);
			 count = registerBeanDefinitions(doc, resource);
			System.out.println(" loadBeanDefinitions ");
		}catch (Exception ex){
			ex.printStackTrace();
		}
		return count;
	}

	public int registerBeanDefinitions(Document doc, Resource resource) {
		//**待扩展BeanDefinitionDocumentReader documentReader = createBeanDefinitionDocumentReader();
		MyDefaultBeanDefinitionDocumentReader documentReader=
				new MyDefaultBeanDefinitionDocumentReader();
		MyXmlReaderContext myXmlReaderContext=new
				MyXmlReaderContext(this,resource);
		documentReader.registerBeanDefinitions(doc, myXmlReaderContext);
		return  0;
	}



	DocumentLoader documentLoader = new DefaultDocumentLoader();
	private EntityResolver entityResolver;
	private ErrorHandler errorHandler = new SimpleSaxErrorHandler(logger);
	private	boolean namespaceAware = false;

	protected Document doLoadDocument(InputSource inputSource, Resource resource) throws Exception {

		ResourceLoader resourceLoader = getResourceLoader();
		this.entityResolver = new ResourceEntityResolver(resourceLoader);

		return documentLoader.loadDocument(
				inputSource,
				entityResolver,
				this.errorHandler,
				XmlValidationModeDetector.VALIDATION_XSD,
				namespaceAware
		);

	}
}
